package RequestHandler;

import Request.*;

public class Dispatcher extends Thread {
    private RequestQueue requestQueue;
    private WorkerPool workerPool;
    
    private boolean quit = false;
    
    public Dispatcher(RequestQueue requestQueue, WorkerPool workerPool) {
        this.requestQueue = requestQueue;
        this.workerPool = workerPool;
    }   
    
    public void run() {
        while (!quit) {
            Request request;
            Worker worker;
            try {
                do {
                    request = getNextRequest();
                    if (request == null) {
                        sleep(500);
                    }
                } while (request == null && !quit);
                
                do {
                    worker = getNextWorker();
                    if (worker == null) {
                        sleep(500);
                    }
                }
                while (worker == null && !quit);
                
                if (!(request == null || worker == null)) {
                    dispatchRequest(worker, request);
                }
            }
            catch (Exception e) {
                
            }
        }
    }
    
    private void dispatchRequest(Worker worker, Request request) {
        request.execute(worker);
    }

    private Worker getNextWorker() {
        return workerPool.getAvailableWorker();
    }
    
    private Request getNextRequest() {
        return requestQueue.getNextRequest();
    }
    
    public void quit() {
        quit = true;
    }
    
}